<template>
  <div class="setting-flow">
    <!--S 头部 -->
    <div class="setting-flow-header">
      <el-row class="setting-flow-header-left" type="flex">
        <p class="return-btn" @click="checkModified(goBack, true)"><i class="iconfont icon-arrow-left"></i>{{$t('common.base.back')}}</p>
        <div>
          <el-row type="flex" style="max-width: 185px;">
            <el-popover placement="bottom" width="224" trigger="click">
              <div class="choose-color-box">
                <div
                  v-for="color in taskTypeColor"
                  :key="color"
                  @click="taskTypeConfig.config.color = color"
                  :style="{ background: color }"
                >
                  <i class="el-icon-check" v-if="taskTypeConfig.config.color === color"></i>
                </div>
              </div>
              <el-tooltip
                slot="reference"
                effect="dark"
                :content="$t('task.setting.taskTypeSetting.flow.tip1')"
                placement="bottom"
              >
                <i class="type-color" :style="{ background: taskTypeConfig.config.color }"></i>
              </el-tooltip>
            </el-popover>
            <div>

              <el-tooltip
                effect="dark"
                :content="$t('task.setting.taskTypeSetting.flow.tip2')"
                placement="bottom"
              >
                <el-input
                  ref="editor"
                  class="type-name"
                  :value="taskTypeName"
                  @focus="isFocus=true"
                  @blur="isFocus=false"
                  @input="changeTaskTypeName"
                  :placeholder="$t('task.setting.taskTypeSetting.flow.placeholder1')"
                >
                  <template slot="append" v-if="!isFocus"><i class="iconfont icon-edit-square" @click="onModify"></i></template>
                </el-input>
              </el-tooltip>
            </div>
          </el-row>
        </div>
      </el-row>
      <el-row class="setting-flow-header-step" type="flex">
        <div
          v-for="(step, idx) in settingStep"
          :key="step.stepName"
          @click="clickTab(idx)"
          :class="idx === currTab && 'active'"
        >
          <i>{{ idx + 1 }}</i>
          <div class="step-name">{{ step.stepName }}</div>
        </div>
      </el-row>
      <div class="setting-flow-header-right">
        <el-button
          class="header-save-btn"
          plain
          @click="submit(true)"
          :loading="pending"
        >{{$t('common.base.save')}}</el-button
        >
      </div>
    </div>
    <!--E 头部 -->

    <!-- 设置页  -->
    <keep-alive>
      <component
        ref="comp"
        :is="settingStep[currTab].compName"
        :task-type-id="taskTypeId"
        :isUpdate="isUpdate"
        :taskTypeName="taskTypeName"
        :isShowPlanStartTime='isShowPlanStartTime'
        :isShowPlanEndTime='isShowPlanEndTime'
        :intelligence-data="intelligentConfig"
        @intelligence="checkIntelligence"
      ></component>
    </keep-alive>
  </div>
</template>

<script>
import http from '@src/util/http';
import { isCalendar } from '@src/util/CalendarUtil';
// api
import * as TaskApi from '@src/api/TaskApi.ts';
import * as SettingApi from '@src/api/SettingApi.ts';
// model
import TaskConfig from '@model/types/setting/task/TaskConfig';
import TaskApprover from '@model/types/setting/task/TaskApprover';
// utils
import { parse } from '@src/util/querystring';
import _ from 'lodash'
import {isEmpty, isFunction} from '@src/util/type'
import { getRootWindow } from '@src/util/dom'
// components
import FlowSettingPanel from './tabs/FlowSettingPanel';
import OtherSettingPanel from './tabs/OtherSettingPanel';
import CardSettingPanel from './tabs/CardSettingPanel';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
import { GrayFunctionEnum } from 'pub-bbx-global/pageType/dist/grayFunction'

const { isOpenMultiLanguage } = useFormMultiLanguage()
const TASK_TYPE_COLOR = [
  'rgb(115,127,124)',
  'rgb(38,111,255)',
  'rgb(82,85,255)',
  'rgb(133,82,255)',
  'rgb(188,82,255)',
  'rgb(255,82,212)',
  'rgb(255,149,38)',
  'rgb(110,207,64)',
  'rgb(0,184,213)',
  'rgb(11,161,148)'
];

export default {
  name: 'setting-flow',
  provide() {
    return {
      taskFlowData: this.$data,
    };
  },
  data() {
    return {
      taskTypeId: '',
      taskTypeName: '',
      taskTypeConfig: new TaskConfig(),
      currTab: 0,

      initTaskTypeConfig: new TaskConfig(),
      pending: false,
      isCalendar,
      isShowPlanStartTime: false,
      isShowPlanEndTime: false,
      intelligentConfig: {},
      isCheckIntelligence: true,
      isUpdate: false,
      isFocus: false,
      visible:false,
      // 会存在点击保存再快速切换到组件设置组件时，会出现保存提示，其实保存肯定能完成，没必要进行提示
      isShowSave: true
    };
  },
  watch: {
    currTab(val) {
      if(val == 1 && this.isCalendar) {
        this.getTaskFields()
      }
    },
  },
  computed: {
    // 是否开启了流程节点灰度
    isOpenTaskFlowExtend() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.[GrayFunctionEnum.TaskFlowExtend] ?? false // 工单流程节点灰度
    },
    taskTypeColor() {
      return TASK_TYPE_COLOR;
    },
    settingStep() {
      return [
        {
          stepName: this.$t('event.setting.constant.setting_step.name1'),
          compName: 'flow-setting-panel',
        },
        {
          stepName: this.$t('event.setting.constant.setting_step.name2'),
          compName: 'other-setting-panel',
        },
        {
          stepName: this.$t('event.setting.constant.setting_step.name3'),
          compName: 'card-setting-panel',
        },
      ];
    },
  },
  methods: {
    onModify() {
      if(isOpenMultiLanguage){
        this.visible = true
        return
      }
      this.$nextTick(() => {
        this.$refs.editor.$el.querySelector('input').focus();
      });
    },
    async getTaskFields() {
      try {
        let fields = await TaskApi.getAllFields({
          tableName: 'task',
          typeId: this.taskTypeId,
          isFromSetting: false,
        });
        this.fields = fields || [];
        let planStartTimeField = this.fields.filter(field => field.formType == 'planStartTime')[0] || {}
        let planEndTimeField = this.fields.filter(field => field.formType == 'planEndTime')[0] || {}
        this.isShowPlanStartTime = isEmpty(planStartTimeField) ? false : true
        this.isShowPlanEndTime = isEmpty(planEndTimeField) ? false : true
        this.fetchTasktype();
      } catch (error) {
        console.error('fetch task getAllFields => err', error);
      }
    },
    goBack() {
      let fromId = window.frameElement.getAttribute('fromid');
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskTypeManage,
        reload: true,
        titleKey: this.$t('task.setting.taskTypeSettings'),
        // fromId
      })
    },
    clickTab(idx) {
      this.isUpdate = false
      setTimeout(() => {
        this.isUpdate = true
      }, 100)
      if(this.currTab === idx) return;
      this.checkModified(() => {
        this.currTab = idx;
      });
    },
    /** 修改工单类型名称 */
    changeTaskTypeName(val) {
      this.taskTypeConfig.name = val;
      this.taskTypeName = val;
      if(isOpenMultiLanguage){
        this.taskTypeConfig.nameLanguage['zh'] = val
      }
    },
    /** 格式化工单类型名称 */
    formatTaskTypeName(name) {
      if(name.length > 9) {
        return `${name.slice(0, 9) }...`;
      }

      return name;
    },
    /** 兼容旧审批结构 */
    compatibleOldApprove(setting = {}) {
      let {leader, level, approvers} = setting;
      if(level === undefined) {
        switch(leader) {
        case undefined:
          if(approvers && approvers.length > 0) {
            leader = 'users';
            level = 1;
          }else {
            level = 0;
          }
          break;
        default: 
          level = 0;
          break
        }
      }

      if(leader === 'none' && !level === 3){
        level = 0;
        leader = '';
      }
      return {
        ...setting,
        leader,
        level
      };
    },
    /** 转化getOne接口返回的数据 */
    convertTaskTypeConfig(taskTypeConfig) {
      let { flowSetting, isLeader, pauseApprovers, planRemindSetting, delayBack, config, overTimeSetting } = taskTypeConfig;

      if(this.isCalendar){
        let planTimeType=planRemindSetting.planType||'';
        let {isShowPlanStartTime, isShowPlanEndTime } = this
        if((!isShowPlanStartTime && planTimeType == 1) || (!isShowPlanEndTime && planTimeType == 2) || (!isShowPlanStartTime && !isShowPlanEndTime)) planTimeType = ''
        planRemindSetting.planTimeType=planTimeType?parseInt(planTimeType):'';
      }
      taskTypeConfig.planRemindSetting = {
        ...new TaskConfig().planRemindSetting,
        ...planRemindSetting
      };
      
      
      taskTypeConfig.delayBack = delayBack === 'true';
      taskTypeConfig.allowPause = Boolean(taskTypeConfig.allowPause);
      taskTypeConfig.allowCancel = Boolean(taskTypeConfig.allowCancel);

      if(isLeader == 1) {
        isLeader = 'leader';
      }else if(isLeader == 2) {
        isLeader = 'none';
      }else if(isLeader == 3) {
        isLeader = 'users';
      }else if(isLeader == 4) {
        isLeader = 'createUser';
      }else if(isLeader == 5) {
        isLeader = 'allotUser';
      }else if(isLeader == 6 && pauseApprovers[0]) {
        isLeader = `formUser_${pauseApprovers[0].taskTemplateId}`;
      }else if(isLeader == 7) {
        isLeader = 'userAdmin';
      }else if(isLeader == 8) {
        isLeader = 'promoter';
      }else {
        isLeader = 'users';
      }

      taskTypeConfig.pauseApproveSetting = this.compatibleOldApprove({leader: isLeader, approvers: pauseApprovers, multiApproverSetting: []});
      
      // 流程审批格式转化
      Object.keys(flowSetting).forEach(key => {
        let {state, setOut, ttid, overTime, leader, approvers, conditions, level, vipApprove, vipApproveSetting,  multiApproverSetting, reallotAppr, approveEditReceipt, questionId, startByFaceId = false, finishByFaceId = false, finishOnlinePay = false } = flowSetting[key];

        if (vipApprove) {
          // 如果有高级设置的话
          level = 4
        } else {
          level = level
        }
        // 兼容旧审批格式
        let approveSetting = this.compatibleOldApprove({
          leader,
          approvers,
          conditions,
          level,
          multiApproverSetting,
          vipApprove,
          vipApproveSetting,
        });

        leader = leader === 'none' ? '' : leader;
        if(key === 'autoReview') {
          // 自动回访开关
          taskTypeConfig.autoReviewState = flowSetting[key].state;
        }else if(key === 'off') {
          // 取消工单设置
          taskTypeConfig.allowCancel = flowSetting[key].state;

          taskTypeConfig.cancelApproveSetting = approveSetting;

          console.log(taskTypeConfig.cancelApproveSetting, 'taskTypeConfig.cancelApproveSetting')

        }else if(key === 'allot'){
          taskTypeConfig.flowSetting[key] = {
            state,
            ttid,
            overTime,
            approveSetting,
            transferApprove:this.compatibleOldApprove(taskTypeConfig.flowSetting[key].transferApprove),
          }
          this.$set(taskTypeConfig.flowSetting[key], 'reallotAppr', reallotAppr !== 'none');
        }else {
          taskTypeConfig.flowSetting[key] = {
            state,
            setOut,
            ttid,
            overTime,
            approveSetting,
            questionId,
            startByFaceId,
            finishByFaceId,
            finishOnlinePay,
          }

          // // 转派需要审批开关
          // if(key === 'allot') {
          //   this.$set(taskTypeConfig.flowSetting[key], 'reallotAppr', reallotAppr !== 'none');
          // }
          if(key == 'finish') {
            this.$set(taskTypeConfig.flowSetting[key], 'approveEditReceipt', approveEditReceipt == true);
          }
          if(key === 'pause') {
            taskTypeConfig.pauseApproveSetting = approveSetting;
          }
        }
      })

      // 兼容旧超时提醒设置
      if(config.newOverTimeSetting === undefined || (config.newOverTimeSetting && config.newOverTimeSetting.length === 0)) {
        taskTypeConfig.taskOverTimeModels = taskTypeConfig.taskOverTimeModels.map(item => {
          return {
            ...item,
            ...overTimeSetting,
            overTimeStatus: true,
            remindType: overTimeSetting.remindType ?? null,
            reminders: overTimeSetting.reminders || []
          }
        })
      }else {
        taskTypeConfig.taskOverTimeModels = config.newOverTimeSetting.map(item => {
          return {
            ...item,
            remindType: item.remindType ?? null,
            overTimeStatus: !!item.overTimeStatus,
            reminders: item.reminders || [],
            roleIds: item.roleIds || []
          }
        })
      }

      delete taskTypeConfig.isLeader;
      delete taskTypeConfig.pauseApprovers;

      return taskTypeConfig;
    },
    /**
     * 智能质检回显数据
     */
    buildIntelligentConfig(data) {
      if(!data.minPictureCheckScore) data.minPictureCheckScore = undefined
      if(!data.minTaskCheckCount) data.minTaskCheckCount = undefined
      if(!data.minTaskCheckScore) data.minTaskCheckScore = undefined
      if(!data.examplePictures) data.examplePictures = []
      if(!data.taskCheckFields) data.taskCheckFields = []
      if(data.examplePictures) {
        data.examplePictures = data?.examplePictures.map(item => {
          return {
            ...item,
            filename: item.fileName,
            url: item.ossUrl,
            id: item.fileId
          }
        })
      }
      return data
    },
    /**
     * 获取工单设置的除组件外的其他信息
     */
    async fetchTasktype(id) {
      this.isUpdate = false
      try {
        let params = {
          id: this.taskTypeId,
        };

        let res = await TaskApi.getTaskType(params);

        this.isUpdate = true

        // 处理智能质检数据并存储
        if(res.data?.config?.intelligentConfig){
          this.intelligentConfig = this.buildIntelligentConfig(res.data.config.intelligentConfig)
        }
        // 转化获取到的结果
        this.taskTypeConfig = this.convertTaskTypeConfig(Object.assign(this.taskTypeConfig, res.data));
        this.initTaskTypeConfig = _.cloneDeep(this.taskTypeConfig);
        this.taskTypeName = this.formatTaskTypeName(this.taskTypeConfig.name);

        // 是否传递计划时间
        const calendarRes = await http.get('/setting/check/calendar');
        let calendarStatus = calendarRes?.data?.status == 2;

        // 传递给FlowSetting组件工单类型名称
        this.$eventBus.$emit('setting_task_type_name', this.taskTypeConfig.name);
        // 判断是否有设置服务报告模板
        if (JSON.stringify(res.data.reportSetting) == '{}') {
          let reportSetting = {
            tenantFields: ['name', 'phone', 'email', 'address', 'portal'],
            customerFields: ['name', 'product', 'address', 'linkman'],
            taskFields: calendarStatus ? ['taskNo', 'executor'] : ['taskNo', 'planTime', 'executor'],
            receiptFields: ['sparepart', 'service', 'autograph'],
          };
          let reportForm = {};
          reportForm.id = this.taskTypeId;
          reportForm.reportSetting = reportSetting;

          try {
            let res = await TaskApi.saveSystemReport(reportForm);
            if (res.status == 0) {
              console.log('默认回执报告设置已保存');
            }
          } catch (err) {
            console.error('设置默认回执报告出错 => err', err);
          }
        }
        // 初始化工单流程配置
       this.$eventBus.$emit('init_flow_setting_task');

      } catch (err) {
        console.error('fetch Tasktype => err', err);
      }
    },
    /** 更新工单类型颜色和名称 */
    // async updateTaskTypeNameAndColor() {
    //   try {
    //     let params =  {
    //       id: this.taskTypeId,
    //       name: this.taskTypeConfig.name,
    //       color: this.taskTypeConfig.config.color
    //     }
    //     await TaskApi.updateTaskTypeNameAndColor(params);
    //   } catch (error) {
    //     console.error(error);
    //   }
    // },
    /** 右上角保存按钮 */
    async submit(flag = false,calc) {
      this.isShowSave = false;
      if (!this.$refs.comp.submit) return;

      let name = this.taskTypeConfig.name;
      if (name === '') {
        return this.$platform.notification({
          title: this.$t('task.setting.taskTypeSetting.flow.tip3'),
          type: 'error'
        });
      }
      if(name.length > 100) {
        return this.$platform.notification({
          title: this.$t('common.validate.maxLen', {limit: '100'}),
          type: 'error'
        });
      }
      // if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(name)) {
      //   return this.$platform.notification({
      //     title: this.$t('task.setting.taskTypeSetting.flow.tip5'),
      //     type: 'error'
      //   });
      // }

      let nameAndColor = {
        name: this.taskTypeConfig.name,
        color: this.taskTypeConfig.config.color
      };
      this.pending = true;
      try {
        const res = await this.$refs.comp.submit(nameAndColor, flag);
        if(this.isOpenTaskFlowExtend && res === true) return;

        // await this.updateTaskTypeNameAndColor();
        if(this.isCheckIntelligence || this.isOpenTaskFlowExtend) {
          await this.fetchTasktype();
          // 消息&附加组件回调
          if(isFunction(calc)) calc();
        }
      } catch (error) {
        console.error(error);
      }finally {
        this.pending = false;
        this.isShowSave = true;
      }
    },
    checkIntelligence(value) {
      this.isCheckIntelligence = value
    },
    /**
     * @description 检查当前tab页是否有修改
     * @param {function} bc 回调函数
     * @param {boolean} isisReturn 是否是返回操作
     */
    async checkModified(bc, isReturn = false) {
      let isModified = false;
      if(this.$refs.comp.checkModified && this.isShowSave) {
        isModified = this.$refs.comp.checkModified();
      }

      let confirmObj = {
        content: isReturn ? this.$t('event.setting.serviceEventTypeSetting.flow.tips1') : this.$t('event.setting.serviceEventTypeSetting.flow.tips2'),
        confirmText: isReturn ? this.$t('common.base.leave') : this.$t('common.base.save'),
        cancelText: isReturn ? this.$t('common.base.cancel') : this.$t('common.base.notSaveForNow')
      }

      if(isModified) {
        this.$confirm(confirmObj.content, '', {
          confirmButtonText: confirmObj.confirmText,
          cancelButtonText: confirmObj.cancelText,
          type: 'warning',
          showClose: false,
          closeOnClickModal: false
        }).then(async () => {
          // 保存
          if(!isReturn) await this.submit();
          setTimeout(() => {
            bc();
          }, 200)
        }).catch(() => {
          this.isUpdate = false
          setTimeout(() => {
            this.isUpdate = true
          }, 200)
          // 取消
          if(isReturn) return;
          // 暂不保存
          if(!isReturn && this.$refs.comp.resetInit) {
            this.$refs.comp.resetInit();
          }
          bc();
        });
      }else {
        bc();
      }
     
    },
  },
  mounted() {
    let query = parse(window.location.search) || {};
    this.taskTypeId = query.taskTypeId;
    if (this.taskTypeId) {
      if(this.isCalendar) {
        this.getTaskFields()
      }else { // getTaskFields方法里面有调用fetchTasktype，避免多调用一次
        this.fetchTasktype();
      }
    }
    this.$eventBus.$on('task_custom_node_save', this.submit)
  },
  beforeDestroy() {
    this.$eventBus.$off('task_custom_node_save')
  },
  components: {
    [FlowSettingPanel.name]: FlowSettingPanel,
    [OtherSettingPanel.name]: OtherSettingPanel,
    [CardSettingPanel.name]: CardSettingPanel,
  },
};
</script>
<style lang="scss" src="./taskFlow.scss" scoped></style>
